package edu.ynu.se.xiecheng.achitectureclass.project.config;

import edu.ynu.se.xiecheng.achitectureclass.project.interceptor.LoginCheckInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration // 配置类
public class WebConfig implements WebMvcConfigurer {

    private final LoginCheckInterceptor loginCheckInterceptor;

    // 推荐使用构造函数注入
    @Autowired
    public WebConfig(LoginCheckInterceptor loginCheckInterceptor) {
        this.loginCheckInterceptor = loginCheckInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginCheckInterceptor)
                .addPathPatterns("/**") // 拦截所有路径
                .excludePathPatterns(
                        "/api/auth/login",
                        "/login",
                        "/capture",
                        "/static/**",
                        "/css/**",
                        "/js/**",
                        "/api/token/camera",
                        "/api/token/**",
                        "/images/**",
                        "/favicon.ico",
                        "/dist/**",
                        "/api/sensor/sub-table-data",
                        "/api/sensor/soil-data",
                        "/api/data/camera/**"
                ); // 排除登录、注册和静态资源路径
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080", "http://localhost:5173/") // 允许的域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}
